import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 47. 全排列 II
 * https://leetcode.cn/problems/permutations-ii/description/
 */
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;
    boolean[] check;

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        check = new boolean[n];
        ret = new LinkedList<>();
        path = new LinkedList<>();
        dfs(nums);
        return ret;
    }

    public void dfs(int[] nums) {
        if(nums.length == path.size()) {
            ret.add(new LinkedList<>(path));
            return;
        }

        for(int i = 0; i < nums.length; i++) {
            if(!check[i] && (i == 0 || nums[i] != nums[i - 1] || check[i - 1])) {
                path.add(nums[i]);
                check[i] = true;

                dfs(nums);

                path.remove(path.size() - 1);
                check[i] = false;
            }
        }
    }
}